package cn.edu.gduf.luowowo.website.web.controller;

import cn.edu.gduf.luowowo.cache.service.IUserInfoRedisService;
import cn.edu.gduf.luowowo.common.util.Consts;
import cn.edu.gduf.luowowo.common.util.RedisKeys;
import cn.edu.gduf.luowowo.member.domain.UserInfo;
import cn.edu.gduf.luowowo.member.service.IUserInfoService;
import cn.edu.gduf.luowowo.website.annotation.UserParam;
import cn.edu.gduf.luowowo.website.util.CookieUtil;
import cn.edu.gduf.luowowo.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
public class ImageController {

    @Reference
    private IUserInfoService userInfoService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Value("${file.path}")
    private String filePath;

    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }

    @RequestMapping("/upload/file")
    @ResponseBody
    public Object headerImg(MultipartFile files, @UserParam UserInfo userInfo, HttpServletRequest request){

        System.out.println(files);
        String filename = UploadUtil.upload(files, filePath);
        System.out.println(filename);
        userInfoService.updateHearderById("/"+filename,userInfo.getId());
        userInfo.setHeadImgUrl("/" + filename);
        String token = CookieUtil.getToken(request);
        String key = RedisKeys.USER_TOKEN.join(token);
        userInfoRedisService.addTokenToRedis(key,userInfo, Consts.USER_INFO_TOKEN_VAI_TIME);
        request.getSession().setAttribute("userInfo",userInfo);
        return filename;
    }

}
